package com.example.administrator.fangbook.read.view.readView;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

import org.geometerplus.fbreader.Paths;
import org.geometerplus.zlibrary.core.application.ZLApplication;
import org.geometerplus.zlibrary.core.util.SystemInfo;
import org.geometerplus.zlibrary.core.view.ZLView;
import org.geometerplus.zlibrary.core.view.ZLViewEnums;
import org.geometerplus.zlibrary.ui.android.view.ZLAndroidPaintContext;
import org.geometerplus.zlibrary.ui.android.view.animation.AnimationManager;

/**
 * 阅读View
 */
public class ZLAndroidWidget extends View {

    private AnimationManager mAnimationManager;
    /**
     * 存储路径
     */
    private SystemInfo mSystemInfo;
    private int mWidth, mHeight = -1;

    public ZLAndroidWidget(Context context) {
        super(context);
        init(context);
    }

    public ZLAndroidWidget(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public ZLAndroidWidget(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        mSystemInfo = Paths.systemInfo(context);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        if (mAnimationManager != null) {
            this.mWidth = w;
            this.mHeight = h;
            mAnimationManager.setSize(w, h);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (mAnimationManager != null) {
            mAnimationManager.draw(canvas);
        }
    }

    public final void setAnimationManager(AnimationManager animationManager) {
        mAnimationManager = animationManager;
    }

    /**
     * 重新绘制
     */
    public void repaint() {
        postInvalidate();
    }

    /**
     * 根据传入的bitmap和页面坐标，把信息绘制到bitmap上
     *
     * @param emptyBitmap
     * @param index
     */
    public void drawOnBitmap(Bitmap emptyBitmap, ZLViewEnums.PageIndex index) {
        //获取FBReader中的View
        final ZLView view = ZLApplication.Instance().getCurrentView();
        if (view == null) {
            return;
        }
        ZLAndroidPaintContext mPaintContext = new ZLAndroidPaintContext(mSystemInfo,
                new Canvas(emptyBitmap),
                new ZLAndroidPaintContext.Geometry(mWidth, mHeight, mWidth, mHeight, 0, 0), 0);
        //由FBReader中的View绘制
        view.paint(mPaintContext, index);
    }
}
